<template>
    <div class="app-container">
        <el-card class="operate-container" shadow="never">
            <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
                <el-form-item label="搜索：">
                    <el-input v-model="listQuery.name" class="input-width" placeholder="请输入巡演名称" clearable></el-input>
                </el-form-item>
            </el-form>
            <div style="display: flex;">
                <el-button
                    style="float:right"
                    type="primary"
                    @click="handleSearchList()"
                    size="small">
                    查询搜索
                </el-button>
                <el-button
                    style="float:right;margin-right: 15px"
                    @click="handleResetSearch()"
                    size="small">
                    重置
                </el-button>
                <el-button size="mini" class="btn-add" @click="createAdd()" >添加巡演关联</el-button>
            </div>
        </el-card>
        <div class="table-container">
            <el-table ref="adminTable"
                    :data="list"
                    style="width: 100%;"
                    v-loading="listLoading" border>
                <el-table-column label="ID" width="100" align="center">
                    <template slot-scope="scope">{{scope.row.id}}</template>
                </el-table-column>
                <el-table-column label="巡演名称" align="center">
                    <template slot-scope="scope">
                        <!-- {{ scope.row.name}} -->
                        <div v-html="hightLight(listQuery.name, scope.row.name)"></div>
                    </template>
                </el-table-column>
                <el-table-column label="已关联活动" align="center">
                    <template slot-scope="scope">{{scope.row.relatedActivity }}</template>
                </el-table-column>
                <el-table-column label="最后编辑时间" width="160" align="center">
                    <template slot-scope="scope">{{scope.row.updateTime | formatDateTime}}</template>
                </el-table-column>
                <el-table-column label="最后操作人" width="160" align="center">
                    <template slot-scope="scope">{{scope.row.updateUsername}}</template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini"
                                    type="text"
                                    @click="handleUpdate(scope.$index, scope.row)">管理
                        </el-button>
                        <el-button size="mini"
                                    type="text"
                                    @click="handleDelete(scope.$index, scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery.pageNum"
                :page-size="listQuery.pageSize"
                :page-sizes="[10,15,20]"
                :total="total">
            </el-pagination>
        </div>

        <el-dialog
            :title="'添加/编辑活动'"
            :visible.sync="visible"
            width="55%">
            <el-form :model="activityResource"
                    ref="thirdForm"
                    :rules="rules"
                    label-width="200px" size="small">
                <el-form-item label="巡演名称：" prop="name">
                    <el-input v-model="activityResource.name" class="input-width" placeholder="请输入巡演名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="巡演关联：" >
                    <div style="position: relative;">
                        <el-input type="text"  class="input-width" v-model="searchQuery" @input="filterOptions"  placeholder="请输入要关联的活动名称/ID" clearable></el-input>
                        <div class="select-div" v-if="isShow">
                            <div v-for="(option, index) in options" :key="index">
                                <input type="checkbox" :value="option" v-model="selectedOptions" />
                                <label>{{ option.zhCnName }} | {{ option.zhHkName }}</label>
                            </div>
                            <div>
                                <el-button @click="cancelName()" size="small">取 消</el-button>
                                <el-button @click="addName()" size="small">确 定</el-button>
                            </div>
                        </div>
                        <div class="select-arr" v-if="ischecked">
                            <div class="div1" v-for="(item, index) in selectedOptions">
                                <div class="div2">
                                    <div class="div4">{{ item.zhCnName }}</div>
                                    <div>{{ item.address }}</div>
                                    <div>{{ item.startTime }} - {{ item.endTime }}</div>
                                </div>
                                <div class="div3">
                                    <i class="el-icon-close" @click="delData(index)"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="visible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="dialogConfirm('thirdForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { toursList, toursSearch, toursLook, toursAdd, toursDelete, toursRelate, activityList, fetchAllResourceList } from '@/api/app';
const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    name: null,
};
const defaultR = {
    activityIds: [],
    name: null,
};
export default{
    data() {
        return {
            listQuery: Object.assign({}, defaultListQuery),
            list: [],
            listLoading: false,
            total: 0,
            visible: false,
            activityResource: Object.assign({}, defaultR),
            rules: {
                name: [
                    { required: true, message: '请填写巡演名称' }
                ],
                selectedOptions: [
                    { required: true, message: '请填输入关联活动' }
                ],
            },
            isEdit: false,
            searchQuery: '',
            selectedOptions: [],
            options: [],
            isShow: false,
            ischecked: false,
            btnMenu: {
                edit: true,
                delete: true,
            },
        }
    },
    created() {
        const menu = JSON.parse(localStorage.getItem('listMenu'));
        const item = menu.filter(item => item.title === '巡演关联管理')[0];
        fetchAllResourceList({menuId: item.id }).then(res => {
            res.data.forEach(dom => {
            if (dom.component === '' && dom.name === '后台角色管理') {
                this.btnMenu.edit = false;
            }
            if (dom.component === '' && dom.name === '后台角色删除') {
                this.btnMenu.delete = false;
            }
            });
        });
        this.getList();
    },
    computed: {
        filteredOptions() {
            return this.options.filter(option =>
                option.toLowerCase().includes(this.searchQuery.toLowerCase())
            );
        }
    },
    methods: {
        hightLight (keyWord, suggtion) {
            // 使用 regexp 构造函数，因为这里要匹配的是一个变量
            let newSrt = null;
            const reg = new RegExp(keyWord, 'ig')
            if (keyWord && suggtion) {
                newSrt = String(suggtion).replace(reg, function (p) {
                    return '<span style="color: #409EFF">' + p + '</span>'
                })
            } else {
                newSrt = suggtion;
            }
            return newSrt
        },
        filterOptions() {
            // console.log(this.searchQuery);
            this.options = [];
            if (this.searchQuery) {
                this.isShow = true;
                activityList({activityName: this.searchQuery}).then(res => {
                    this.options = res.data.records;
                });
            }
        },
        cancelName() {
            this.selectedOptions = [];
            this.isShow = false;
            this.ischecked = false
        },
        addName() {
            // console.log(this.selectedOptions);
            this.isShow = false;
            if (this.selectedOptions.length > 0) {
                this.ischecked = true;
            }
        },
        delData(index) {
            // console.log(index);
            this.selectedOptions.splice(index, 1);
        },
        getList() {
            toursList(this.listQuery).then(res => {
                this.list = res.data.records;
                this.total = res.data.total;
            });
        },
        createAdd() {
            this.isEdit = false;
            this.visible = true;
            this.activityResource = Object({}, defaultR);
        },
        handleUpdate(index, row) {
            this.isEdit = true;
            this.visible = true;
            this.activityResource = row;
        },
        handleDelete(index, row) {
            this.$confirm('是否要删除该活动?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                toursDelete({activityToursId: row.id}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getList();
                });
            });
        },
        dialogConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isEdit) {
                        toursRelate(this.activityResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                            this.visible = false;
                            this.getList();
                        });
                    } else {
                        this.activityResource.activityIds = [];
                        if (this.selectedOptions.length > 0) {
                            this.selectedOptions.forEach(item => {
                                this.activityResource.activityIds.push(item.activityId);
                            });
                        }
                        toursAdd(this.activityResource).then(res => {
                            this.$message({
                                type: 'success',
                                message: '操作成功!'
                            });
                            this.visible = false;
                            this.getList();
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        handleResetSearch() {
          this.listQuery = Object.assign({}, defaultListQuery);
          this.getList();
        },
        handleSearchList() {
            this.listQuery.pageNum = 1;
            this.getList();
        },
        handleSizeChange(val) {
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val) {
          this.listQuery.pageNum = val;
          this.getList();
        },
    }
}
</script>

<style lang="scss" scoped>
.input-width {
    width: 360px;
}
.select-div {
    position: absolute;
}
.select-arr {
    display: flex;
    .div1 {
        display: flex;
        background-color: aliceblue;
        margin: 10px;
        padding: 5px 10px;
        .div2 {
            display: flex;
            flex-direction: column;
            // width: 145px;
            .div4 {
                width: 140px;
                overflow: hidden;
                // text-emphasis: ;
            }
        }
        .div3 {
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 30px;
        }
    }
}
</style>
